/**
 * Created by xuelei.kong on 2017/7/16.
 */
var forEach = function (arr, fn) {
    var len = arr.length;
    for (var i = 0; i < len; i++) {
        var tmp = arr[i];
        if (fn.call(tmp, i, tmp) == false) {
            break;
        }
    }

};

function formatDate(date, fmt) {
    var D = new Date(date);
    var o = {
        "M+": D.getMonth() + 1, //月份
        "d+": D.getDate(), //日
        "h+": D.getHours(), //小时
        "m+": D.getMinutes(), //分
        "s+": D.getSeconds(), //秒
        "q+": Math.floor((D.getMonth() + 3) / 3), //季度
        "S": D.getMilliseconds() //毫秒
    };

    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (D.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

var showDatePicker = function (obj, type) {
    if (type === 1) {
        WdatePicker({
            maxDate: $(obj).parents('.filter-wrapper').find(".to").val(),
            onpicked: function () {
                $(obj).blur();
            }
        })
    } else {
        WdatePicker({
            minDate: $(obj).parents('.filter-wrapper').find(".from").val(),
            onpicked: function () {
                $(obj).blur();
            }
        })
    }

};
var app = new Vue({
    el: '#app',
    data: function () {
        return {
            loadingFlag: false,
            ztreeLoadingFlag: false,
            startDate: formatDate(new Date().getTime() - 24 * 60 * 60 * 1000, 'yyyy-MM-dd'),
            endDate: formatDate(new Date().getTime(), 'yyyy-MM-dd'),
            equipmentID: [],
            equipment: [],
            showType: [
                {
                    text: '15分钟',
                    id: 1
                },
                {
                    text: '小时',
                    id: 2
                },
                {
                    text: '天',
                    id: 3
                }
            ],
            type: 1,
            pageIndex: 1,
            pageSize: 10,
            allPage: 10,
            current: 1,
            showItem: 5,
            list: [],
            tableList:[],
            hasList: true,
            hasPagination: false,
            option: {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross',
                        crossStyle: {
                            color: '#999'
                        }
                    }
                },

                legend: {
                    right:'5%',
                    top:'5%',
                    data: [
                        {
                            name: "2016计划用量",
                            icon: 'square',
                            textStyle: {
                                color: "#FF33CC",
                                fontSize: 12
                            }
                        },
                        {
                            name: "计划用量",
                            icon: 'circle',
                            textStyle: {
                                color: "#FFCC33",
                                fontSize: 12
                            }
                        }
                    ]

                },
                grid: {
                    left: '3%',
                    right: '1%',
                    bottom: '0%',
                    containLabel: true
                },
                xAxis: [
                    {

                        name: "月",
                        axisLine: {
                            lineStyle: {
                                color: '#008078'
                            }
                        },
                        axisLabel: {
                            textStyle: {
                                color: '#00f3ff'
                            }
                        },
                        type: 'category',
                        data: [],
                        axisPointer: {
                            type: 'shadow'
                        }
                    }
                ],
                yAxis: [
                    {
                        name: "损耗率",

                        type: 'value',
                        axisLine: {
                            lineStyle: {
                                color: '#008078'
                            }
                        },
                        splitLine: {
                            lineStyle: {
                                type: "doote",
                                color: '#4a6b70'

                            }
                        },
                        axisLabel: {
                            textStyle: {
                                color: '#00f3ff'
                            }
                        }

                    },
                    {
                        name: '损耗率',
                        type: 'value',
                        axisLine: {
                            lineStyle: {
                                color: '#008078'
                            }
                        },
                        splitLine: {
                            lineStyle: {
                                type: "doote",
                                color: '#4a6b70'

                            }
                        },
                        axisLabel: {
                            textStyle: {
                                color: '#00f3ff'
                            }
                        }
                    }
                ],
                series: [
                    {

                        itemStyle: {
                            normal: {
                                color: '#FF33CC'
                            }
                        },

                        name: '2016计划用量',
                        type: 'bar',
                        data: []
                    },

                    {
                        name: '计划用量',
                        type: 'line',
                        yAxisIndex: 1,
                        itemStyle: {
                            normal: {
                                color: '#FFCC33'
                            }
                        },
                        data: []
                    }


                ]
            }


        }
    },
    mounted: function () {
        var that = this;



        //ztree

        // this.loadingFlag = true;
        $.ajax({
            url: "http://180.166.106.206:8086/Data/GetTree",
            type: 'GET',
            success: function (res) {
                console.log(res);
                var code;

                function setCheck() {
                    var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
                        py = $("#py").attr("checked") ? "p" : "",
                        sy = $("#sy").attr("checked") ? "s" : "",
                        pn = $("#pn").attr("checked") ? "p" : "",
                        sn = $("#sn").attr("checked") ? "s" : "",
                        // type = {"Y": py + sy, "N": pn + sn};
                        type = {"Y": "", "N": ""};

                    zTree.setting.check.chkboxType = type;
                    showCode('setting.check.chkboxType = { "Y" : "' + type.Y + '", "N" : "' + type.N + '" };');
                }

                function showCode(str) {
                    if (!code) code = $("#code");
                    code.empty();
                    code.append("<li>" + str + "</li>");
                }

                var setting = {
                    check: {
                        enable: true
                    },

                    data: {
                        simpleData: {
                            enable: true
                        }
                    },

                    view: {
                        fontCss: setHighlight // 高亮一定要设置，setHighlight是自定义方法
                    },

                    callback: {
                        onCheck: onCheck
                    }
                };
                that.ztree = $.fn.zTree.init($("#treeDemo"), setting, res.zNodes);
                that.ztreeLoadingFlag = false;
                console.log(res.zNodes[0]);
                var node = that.ztree.getNodeByParam("id", res.zNodes[0].id);
                that.ztree.checkNode(node);
                that.equipmentID.push(res.zNodes[0].id);
                that.equipment.push(res.zNodes[0].name);


                that.getData();

                // 设置高亮字体
                function setHighlight(treeId, treeNode) {
                    console.log(treeNode);
                    return (treeNode.highlight) ? {
                        color: "#EB6100"
                        // "font-weight": "bold",
                        // "background-color": "#EB6100"
                    } : {color: "#01fcf0", "font-weight": "normal"};
                }


                // var node = zTree.getNodeByParam("id",5001);
                // zTree.selectNode(node);

                setCheck();
                $("#py").bind("change", setCheck);
                $("#sy").bind("change", setCheck);
                $("#pn").bind("change", setCheck);
                $("#sn").bind("change", setCheck);

                function onCheck(e, treeId, treeNode) {
                    var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
                    var nodes = treeObj.getCheckedNodes(true);
                    console.log(nodes);
                    var v = "";
                    that.equipment = [];
                    that.equipmentID = [];
                    for (var i = 0; i < nodes.length; i++) {
                        v += nodes[i].name + ",";
                        if (!nodes[i].children) {

                        }
                        if (nodes[i].id !== treeNode.id) {
                            treeObj.checkNode(nodes[i], false);
                        } else {
                            that.equipmentID.push(nodes[i].id);
                            that.equipment.push(nodes[i].name);

                            that.lineOption.series[0].name = that.equipment[0];
                            that.lineOption.legend.data[0].name = that.equipment[0];
                        }


                    }


                }


            }

        });


    },
    methods: {
        search: function () {

            if (!this.startDate || !this.endDate) {
                alert("请选择起止时间")
            } else if (!this.equipmentID.length) {
                alert('请选择设备');
            } else {
                if (arguments.length) {
                    this.pageIndex = 1;
                }
                this.getData();
            }
        },
        changeType: function (id) {
            this.type = id;
        },
        getData: function () {
            var that = this;
            that.loadingFlag = true;
            that.hasList = true;
            $.ajax({
                url:'http://180.166.106.206:8086/Lost/GetLostLine?id='+this.equipmentID[0]+'&type=4',
                dataType:'json',
                type:"POST",
                success:function (res) {
                    forEach(res.List,function (i, item) {
                        that.option.xAxis[0].data.push(i);
                        that.option.series[0].data.push(res.List[i].Fxyg_Input);
                        that.option.series[1].data.push(res.Plan[i]);
                    });

                    var myChart = echarts.init(document.getElementById('xsfx'));
                    myChart.setOption(that.option);


                }
            });

            $.ajax({
                url: "http://180.166.106.206:8086/Lost/GetLostData?id="+this.equipmentID[0]+"&begin="+this.startDate+"&end="+this.endDate+"&type="+this.type+"&page="+this.pageIndex,
                dataType: 'json',
                type: "POST",
                success: function (res) {
                    console.log(res);
                    that.loadingFlag = false;
                    that.tableList = res.List;
                    if (!that.tableList.length) {
                        that.hasList = false;
                    } else {
                        that.hasPagination = true;
                    }
                    // {value: 1000, name: 'A'},

                }
            });
        },

        searchNode: function () {
            var value = this.$refs.ztreesearch.value;
            if (value == "") return;

            // 获取搜索的节点
            var nodes = this.ztree.getNodesByParamFuzzy("name", value);
            // 关闭所有节点的高亮
            var allNodes = this.ztree.transformToArray(this.ztree.getNodes());
            for (var i = 0; i < allNodes.length; i++) {
                allNodes[i].highlight = false;
                this.ztree.updateNode(allNodes[i]);
            }
            // 展开第一层节点
            this.ztree.expandAll(false);
            this.ztree.expandNode(this.ztree.getNodes()[0], true);
            // 高亮并展开搜索到的节点
            for (var i = 0; i < nodes.length; i++) {
                nodes[i].highlight = true;
                this.ztree.updateNode(nodes[i]); // 更新节点，让高亮生效
                this.ztree.expandNode(nodes[i].getParentNode(), true);
            }
        },
        searchNodeLazy: function () {
            var timeoutId = null;
            var that = this;
            var value = event.target.value;
            if (timeoutId) {
                console.log(222);
                clearTimeout(timeoutId);
            }
            timeoutId = setTimeout(function () {
                console.log(111);
                that.searchNode(value);
            }, 500);
        },
        setViewModel: function (which) {
            this[which] = event.target.value;
        },
        goto: function (page) {
            if (page === this.pageIndex) return;
            this.pageIndex = page;
            //这里可以发送ajax请求
            this.search();
        }

    },
    computed: {
        pages: function () {
            var pag = [];
            if (this.pageIndex < this.showItem) { //如果当前的激活的项 小于要显示的条数
                //总页数和要显示的条数那个大就显示多少条
                var i = Math.min(this.showItem, this.allPage);
                while (i) {
                    pag.unshift(i--);
                }
            } else { //当前页数大于显示页数了
                var middle = this.pageIndex - Math.floor(this.showItem / 2),//从哪里开始
                    i = this.showItem;
                if (middle > (this.allPage - this.showItem)) {
                    middle = (this.allPage - this.showItem) + 1
                }
                while (i--) {
                    pag.push(middle++);
                }
            }
            console.log(pag);
            return pag
        }
    }

});


